//
//  PunchCardViewController.m
//  云律司
//
//  Created by 韦淋 on 2017/6/8.
//  Copyright © 2017年 test. All rights reserved.
//

#import "PunchCardViewController.h"

@interface PunchCardViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,BMKPoiSearchDelegate,BMKRouteSearchDelegate>


{
//    CLLocation *companyLocation;
    CLLocationDistance distance;
    UILabel *timeLable;
    NSTimer *timeNow;
    NSString *nsDateString;
}

@property (nonatomic, strong) BMKMapView *mapView;
@property (nonatomic, strong) BMKLocationService *locService;
@property (nonatomic, strong) BMKGeoCodeSearch *geoCodeSearch;
@property (nonatomic, strong) BMKAnnotationView *mapAnnoView;
@property (nonatomic, strong) BMKPointAnnotation *pointAnnotation;
@property (nonatomic, strong) BMKPoiSearch *poiSearch;
@property (nonatomic, strong) BMKRouteSearch *routeSearch;
@property (nonatomic, readonly) CLLocationCoordinate2D localCoor;
@property (nonatomic, readonly) CLLocationCoordinate2D coor;

@end

@implementation PunchCardViewController

- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = YES;
    //    self.automaticallyAdjustsScrollViewInsets = false;
    [_mapView viewWillAppear];
    _mapView.delegate = self;
    _locService.delegate = self;
    _geoCodeSearch.delegate = self;
    _routeSearch.delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil;
    _locService.delegate = nil;
    _geoCodeSearch.delegate = nil;
    _routeSearch.delegate = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.barTitleLable.text = @"考勤打卡";
    [self initUI];
    [self position];
}

#pragma mark - Getter

#pragma mark - ButtonTarget
- (void)punchIn{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *nowtimeStr = [formatter stringFromDate:datenow];
    NSLog(@"nowtimeStr =  %@",nowtimeStr);
    
    
    //    //存
    //    [[NSUserDefaults standardUserDefaults]setObject:@{@"punchState":@"1"} forKey:@"punchState"];
    //    //取
    //    NSDictionary *dic = [NSMutableDictionary dictionary];
    //    dic =  [[NSUserDefaults standardUserDefaults]objectForKey:@"punchState"];
    if (distance < 500) {
        NSDate *date = [NSDate date];
        NSInteger time = [self compareOneDay:date withFlag:1];
        
        if (time  == 1) {
            NSLog(@"上班迟到");
            [NetworkingManager postUrl:PUNCHCARD_URL dic:@{@"userid":[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"],@"elongitude":[NSString stringWithFormat:@"%f",self.coor.longitude],@"nlatitude":[NSString stringWithFormat:@"%f",self.coor.latitude],@"daka_time":nowtimeStr,@"dakalx":@"1",@"dakatype":@"1",@"dakafl":@"2",@"bz":@"韦淋测试 ",@"gsid":[InfoSingleTon personInfoSingleTon].infoDic[@"cid"],@"create_id":[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"],@"create_date":nowtimeStr} Succeed:^(id responseData) {
                NSLog(@"success:%@",responseData);
                [MBProgressHUD showSuccess:@"已签到"];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            } failure:^(NSError *error) {
                NSLog(@"error:%@",error);
                [MBProgressHUD showError:@"网络异常"];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            }];
        }else{
        NSLog(@"没迟到");
            [NetworkingManager postUrl:PUNCHCARD_URL dic:@{@"userid":[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"],@"elongitude":[NSString stringWithFormat:@"%f",self.coor.longitude],@"nlatitude":[NSString stringWithFormat:@"%f",self.coor.latitude],@"daka_time":nowtimeStr,@"dakalx":@"1",@"dakatype":@"1",@"dakafl":@"1",@"bz":@"韦淋测试 ",@"gsid":[InfoSingleTon personInfoSingleTon].infoDic[@"cid"],@"create_id":[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"],@"create_date":nowtimeStr} Succeed:^(id responseData) {
                NSLog(@"success:%@",responseData);
                [MBProgressHUD showSuccess:@"已签到"];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            } failure:^(NSError *error) {
                NSLog(@"error:%@",error);
                [MBProgressHUD showError:@"网络异常"];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            }];
        }
        
        NSLog(@"上班打卡 ");
        
        
    }
    else{
        NSLog(@"范围外 ");
        NSInteger time = [self compareOneDay:[NSDate date] withFlag:1];
        if (time  == 1) {
            NSLog(@"上班迟到");
            [NetworkingManager postUrl:PUNCHCARD_URL dic:@{@"userid":[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"],@"elongitude":[NSString stringWithFormat:@"%f",self.coor.longitude],@"nlatitude":[NSString stringWithFormat:@"%f",self.coor.latitude],@"daka_time":nowtimeStr,@"dakalx":@"1",@"dakatype":@"2",@"dakafl":@"2",@"bz":@"韦淋测试 ",@"gsid":[InfoSingleTon personInfoSingleTon].infoDic[@"cid"],@"create_id":[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"],@"create_date":nowtimeStr} Succeed:^(id responseData) {
                NSLog(@"success:%@",responseData);
                [MBProgressHUD showSuccess:@"已签到"];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            } failure:^(NSError *error) {
                NSLog(@"error:%@",error);
                [MBProgressHUD showError:@"网络异常"];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            }];
        }else{
            NSLog(@"没迟到");
            [NetworkingManager postUrl:PUNCHCARD_URL dic:@{@"userid":[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"],@"elongitude":[NSString stringWithFormat:@"%f",self.coor.longitude],@"nlatitude":[NSString stringWithFormat:@"%f",self.coor.latitude],@"daka_time":nowtimeStr,@"dakalx":@"1",@"dakatype":@"2",@"dakafl":@"1",@"bz":@"韦淋测试 ",@"gsid":[InfoSingleTon personInfoSingleTon].infoDic[@"cid"],@"create_id":[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"],@"create_date":nowtimeStr} Succeed:^(id responseData) {
                NSLog(@"success:%@",responseData);
                [MBProgressHUD showSuccess:@"已签到"];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            } failure:^(NSError *error) {
                NSLog(@"error:%@",error);
                [MBProgressHUD showError:@"网络异常"];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            }];
        }
        
        NSLog(@"上班打卡 ");
    }
    
}
- (void)punchOut{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *nowtimeStr = [formatter stringFromDate:datenow];
    NSLog(@"nowtimeStr =  %@",nowtimeStr);
    
    
    if (distance < 500) {
        NSInteger time = [self compareOneDay:[NSDate date] withFlag:2];
        if (time  == -1) {
            NSLog(@"早退");
            [NetworkingManager postUrl:PUNCHCARD_URL dic:@{@"userid":[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"],@"elongitude":[NSString stringWithFormat:@"%f",self.coor.longitude],@"nlatitude":[NSString stringWithFormat:@"%f",self.coor.latitude],@"daka_time":nowtimeStr,@"dakalx":@"2",@"dakatype":@"1",@"dakafl":@"5",@"bz":@"韦淋测试 ",@"gsid":[InfoSingleTon personInfoSingleTon].infoDic[@"cid"],@"create_id":[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"],@"create_date":nowtimeStr} Succeed:^(id responseData) {
                NSLog(@"success:%@",responseData);
                [MBProgressHUD showSuccess:@"已打卡"];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            } failure:^(NSError *error) {
                NSLog(@"error:%@",error);
                [MBProgressHUD showError:@"网络异常"];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            }];
        }else{
            NSLog(@"可以下班了");
            [NetworkingManager postUrl:PUNCHCARD_URL dic:@{@"userid":[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"],@"elongitude":[NSString stringWithFormat:@"%f",self.coor.longitude],@"nlatitude":[NSString stringWithFormat:@"%f",self.coor.latitude],@"daka_time":nowtimeStr,@"dakalx":@"2",@"dakatype":@"1",@"dakafl":@"1",@"bz":@"韦淋测试 ",@"gsid":[InfoSingleTon personInfoSingleTon].infoDic[@"cid"],@"create_id":[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"],@"create_date":nowtimeStr} Succeed:^(id responseData) {
                NSLog(@"success:%@",responseData);
                [MBProgressHUD showSuccess:@"已打卡"];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            } failure:^(NSError *error) {
                NSLog(@"error:%@",error);
                [MBProgressHUD showError:@"网络异常"];
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            }];
        }
        NSLog(@"下班打卡 ");
    }
    else{
        NSLog(@"范围外 ");
        [NetworkingManager postUrl:PUNCHCARD_URL dic:@{@"userid":[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"],@"elongitude":[NSString stringWithFormat:@"%f",self.coor.longitude],@"nlatitude":[NSString stringWithFormat:@"%f",self.coor.latitude],@"daka_time":nowtimeStr,@"dakalx":@"2",@"dakatype":@"2",@"dakafl":@"5",@"bz":@"韦淋测试 ",@"gsid":[InfoSingleTon personInfoSingleTon].infoDic[@"cid"],@"create_id":[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"],@"create_date":nowtimeStr} Succeed:^(id responseData) {
            NSLog(@"success:%@",responseData);
            [MBProgressHUD showSuccess:@"已打卡"];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        } failure:^(NSError *error) {
            NSLog(@"error:%@",error);
            [MBProgressHUD showError:@"网络异常"];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    }
}
- (void)checkPunchRecord{
    NSLog(@"查看打卡记录 ");
    PunchRecordViewController *PRVC = [[PunchRecordViewController alloc] init];
    [self.navigationController pushViewController:PRVC animated:YES];
}
#pragma mark ----打卡
- (int)compareOneDay:(NSDate *)oneDay withFlag:(NSInteger)flag
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"HH:mm:ss"];
    NSString *earlyTime = @"09:00:00";
    NSString *afternoonTime = @"18:00:00";
    NSDate *earlyDate = [dateFormatter dateFromString:earlyTime];
    NSDate *afternoonDate = [dateFormatter dateFromString:afternoonTime];

    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr;
    if (flag == 1) {
         anotherDayStr = [dateFormatter stringFromDate:earlyDate];
    }else{
         anotherDayStr = [dateFormatter stringFromDate:afternoonDate];
    }
  
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    
    NSComparisonResult result = [dateA compare:dateB];
    
    if (result == NSOrderedDescending) {
        NSLog(@"oneDay比 anotherDay时间晚");
        return 1;
    }
    else if (result == NSOrderedAscending){
        NSLog(@"oneDay比 anotherDay时间早");
        return -1;
    }
    NSLog(@"两者时间是同一个时间");
    return 0;
}

#pragma mark - Method
- (void)initUI{
    _locService = [[BMKLocationService alloc]init];
    _geoCodeSearch = [[BMKGeoCodeSearch alloc] init];
    _mapAnnoView = [[BMKAnnotationView alloc] init];
    _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(5, 130, self.view.frame.size.width - 10, 250)];
    _mapView.layer.masksToBounds = YES;
    _mapView.layer.cornerRadius = 5;
    
//    _mapView.centerCoordinate = companyLocation.coordinate; //让地图的中心位置在这里
//    [_mapView setCenterCoordinate:companyLocation.coordinate animated:YES];
    
    
    _coor.latitude = 29.59222;
    _coor.longitude = 106.475101;
//    companyLocation = [[CLLocation alloc] initWithLatitude:self.coor.latitude longitude:self.coor.longitude];
    BMKCircle* circle = [BMKCircle circleWithCenterCoordinate:self.coor radius:500];
    
    timeLable = [[UILabel alloc] initWithFrame:CGRectMake(50, 64, self.view.frame.size.width - 10, 60)];
    timeLable.font = [UIFont systemFontOfSize:20];
    NSArray * arrWeek=[NSArray arrayWithObjects:@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六", nil];
    //获取系统时间
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"HH:mm"];
    NSString * locationString=[dateformatter stringFromDate:senddate];
    NSLog(@"-------%@",locationString);
    //获取系统时间
    NSCalendar * cal=[NSCalendar currentCalendar];
    NSUInteger unitFlags=NSCalendarUnitDay|NSCalendarUnitMonth|NSCalendarUnitYear|NSCalendarUnitWeekday;
    NSDateComponents * conponent= [cal components:unitFlags fromDate:senddate];
    NSInteger year=[conponent year];
    NSInteger month=[conponent month];
    NSInteger day=[conponent day];
    NSInteger weekDay = [conponent weekday];
    nsDateString= [NSString stringWithFormat:@"%4ld年%2ld月%2ld日  %@",(long)year,(long)month,(long)day,[arrWeek objectAtIndex:weekDay - 1]];
    NSLog(@"+++++++++++++%@",nsDateString);
    timeNow = [NSTimer scheduledTimerWithTimeInterval:0.0 target:self selector:@selector(timerFunc:) userInfo:nil repeats:YES];
    
    
    UIButton *punchInButton = [UIButton buttonWithType:UIButtonTypeCustom];
    punchInButton.frame = CGRectMake(25, 20, 50, 50);
    punchInButton.titleLabel.textColor = [UIColor whiteColor];
    punchInButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [punchInButton setTitle:@"上班打卡" forState:0];
    [punchInButton setBackgroundImage:[UIImage imageNamed:@"list_04"] forState:0];
    [punchInButton layoutButtonWithEdgInsetsStyle:WxyButtonEdgeInsetsStyleImageTop imageTitleSpacing:120];
    [punchInButton addTarget:self action:@selector(punchIn) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *punchOutButton = [UIButton buttonWithType:UIButtonTypeCustom];
    punchOutButton.frame = CGRectMake(25, 20, 50, 50);
    punchOutButton.titleLabel.textColor = [UIColor whiteColor];
    punchOutButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [punchOutButton setTitle:@"下班打卡" forState:0];
    [punchOutButton setBackgroundImage:[UIImage imageNamed:@"list_04"] forState:0];
    [punchOutButton layoutButtonWithEdgInsetsStyle:WxyButtonEdgeInsetsStyleImageTop imageTitleSpacing:120];
    [punchOutButton addTarget:self action:@selector(punchOut) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *punchInBG = [[UIImageView alloc ]initWithFrame:CGRectMake(50, 450, 100, 100)];
    punchInBG.userInteractionEnabled = YES;
    punchInBG.image = [UIImage imageNamed:@"map_02"];
    
    UIImageView *punchOutBG = [[UIImageView alloc ]initWithFrame:CGRectMake(230, 450, 100, 100)];
    punchOutBG.userInteractionEnabled = YES;
    punchOutBG.image = [UIImage imageNamed:@"map_02"];
    
    UIButton *punchRecord = [UIButton buttonWithType:UIButtonTypeCustom];
    punchRecord.frame = CGRectMake(90, 600, 200, 50);
    punchRecord.layer.masksToBounds = YES;
    punchRecord.layer.cornerRadius = 5;
    punchRecord.backgroundColor = [UIColor colorWithRed:33.0f/255.0f green:180.0f/255.0f blue:237.0f/255.0f alpha:1.0f];
    [punchRecord setTitle:@"打卡记录" forState:0];
    punchRecord.titleLabel.textColor = [UIColor colorWithRed:33.0f/255.0f green:180.0f/255.0f blue:237.0f/255.0f alpha:1.0f];
    punchRecord.titleLabel.font = [UIFont systemFontOfSize:16];
    [punchRecord addTarget:self action:@selector(checkPunchRecord) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:timeLable];
    [self.view addSubview:_mapView];
    [self.view addSubview:punchInBG];
    [self.view addSubview:punchOutBG];
    [self.view addSubview:punchRecord];
    [punchInBG addSubview:punchInButton];
    [punchOutBG addSubview:punchOutButton];
    [_mapView addOverlay:circle];
}
- (void)timerFunc:(NSString *)date
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"HH:mm:ss"];
    
    NSString *timestamp = [formatter stringFromDate:[NSDate date]];
    
    [timeLable setText:[NSString stringWithFormat:@"%@  %@",nsDateString,timestamp]];//时间在变化的语句

}
- (void)position{
    _locService.delegate = self;
    //启动LocationService
    
    _mapView.zoomLevel = 14.1;
    _mapView.showsUserLocation = NO;//是否显示小蓝点，no不显示，我们下面要自定义的
    _mapView.userTrackingMode = BMKUserTrackingModeNone;
    //定位
    [_locService startUserLocationService];
    
    [_mapView removeAnnotation:_pointAnnotation];
    
}
- (void)countDistance{
    CLLocation *location1 = [[CLLocation alloc] initWithLatitude:self.locService.userLocation.location.coordinate.latitude longitude:self.locService.userLocation.location.coordinate.longitude];
    CLLocation *location2 = [[CLLocation alloc] initWithLatitude:self.coor.latitude longitude:self.coor.longitude] ;
    distance = [location1 distanceFromLocation:location2];
}

// Override
- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id <BMKOverlay>)overlay{
    if ([overlay isKindOfClass:[BMKCircle class]]){
        BMKCircleView* circleView = [[BMKCircleView alloc] initWithOverlay:overlay];
        circleView.fillColor = [[UIColor colorWithRed:33.0f/255.0f green:180.0f/255.0f blue:237.0f/255.0f alpha:1.0f] colorWithAlphaComponent:0.5];
        circleView.strokeColor = [[UIColor colorWithRed:102.0f/255.0f green:159.0f/255.0f blue:190.0f/255.0f alpha:1.0f] colorWithAlphaComponent:0.5];
        circleView.lineWidth = 1;
        
        return circleView;
    }
    return nil;
}
//根据polyline设置地图范围
- (void)mapViewFitPolyLine:(BMKPolyline *) polyLine {
    CGFloat ltX, ltY, rbX, rbY;
    if (polyLine.pointCount < 1) {
        return;
    }
    BMKMapPoint pt = polyLine.points[0];
    ltX = pt.x, ltY = pt.y;
    rbX = pt.x, rbY = pt.y;
    for (int i = 1; i < polyLine.pointCount; i++) {
        BMKMapPoint pt = polyLine.points[i];
        if (pt.x < ltX) {
            ltX = pt.x;
        }
        if (pt.x > rbX) {
            rbX = pt.x;
        }
        if (pt.y > ltY) {
            ltY = pt.y;
        }
        if (pt.y < rbY) {
            rbY = pt.y;
        }
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(ltX , ltY);
    rect.size = BMKMapSizeMake(rbX - ltX, rbY - ltY);
    [_mapView setVisibleMapRect:rect];
    _mapView.zoomLevel = _mapView.zoomLevel - 0.3;
}

-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    BMKCoordinateRegion region;
    region.center.latitude  = userLocation.location.coordinate.latitude;
    region.center.longitude = userLocation.location.coordinate.longitude;
    region.span.latitudeDelta  = 0.0001;
    region.span.longitudeDelta = 0.0001;
    _mapView.centerCoordinate = userLocation.location.coordinate;
    //选择一个范围，让地图显示到当前界面
    [_mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
    [self.mapView setZoomEnabled:YES];
    [self.mapView setZoomEnabledWithTap:YES];
    [self.mapView setZoomLevel:16.1];
    

    
    NSLog(@"定位的经度:%f,定位的纬度:%f",userLocation.location.coordinate.longitude,userLocation.location.coordinate.latitude);
    _mapView.showsUserLocation = NO;//显示用户位置
    [_mapView updateLocationData:userLocation];
    //    _mapView.centerCoordinate = userLocation.location.coordinate; //让地图的中心位置在这里
    [_locService stopUserLocationService];
    
    [self countDistance];
    
    _pointAnnotation = [[BMKPointAnnotation alloc] init];
    _pointAnnotation.coordinate = userLocation.location.coordinate;
    _pointAnnotation.title = @"您距离公司还有";
    _pointAnnotation.subtitle = [NSString stringWithFormat:@"%0.2f km",distance/1000];
    [_mapView addAnnotation:_pointAnnotation];
    [_mapView selectAnnotation:_pointAnnotation animated:YES];
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
